package com.jinxin.platform.cdperprotypay.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdperprotypay.excel.ColumnWidthStyleStrategy;
import com.jinxin.platform.cdperprotypay.excel.data.ChargeData;
import com.jinxin.platform.cdperprotypay.excel.data.MeterDatas;
import com.jinxin.platform.cdperprotypay.pojo.bo.SysHouse;
import com.jinxin.platform.cdperprotypay.pojo.domain.ChargeDetail;
import com.jinxin.platform.cdperprotypay.pojo.form.ChargeDetailForm;
import com.jinxin.platform.cdperprotypay.pojo.form.StatisticsForm;
import com.jinxin.platform.cdperprotypay.pojo.vo.StatisticsVo;
import com.jinxin.platform.cdperprotypay.service.ChargeDetailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : zhangpeng
 * @date : 2020-06-29 17:46:03
 **/
@RestController
@RequestMapping("charge/detail")
public class ChargeDetailController {

    @Autowired
    private ChargeDetailService chargeDetailService;

    @PostMapping("/add")
    public JsonResult add(@RequestBody ChargeDetail chargeDetail){
        return chargeDetailService.insert(chargeDetail);
    }

    @PostMapping("/update")
    public JsonResult update(@RequestBody ChargeDetail chargeDetail){
        return chargeDetailService.update(chargeDetail);
    }

    @PostMapping("/findOwe")
    public JsonResult findOwe(ChargeDetailForm chargeDetailForm){
        return chargeDetailService.findOwe(chargeDetailForm);
    }

    @PostMapping("/findOwe2App")
    public JsonResult findOwe2App(ChargeDetailForm chargeDetailForm){
        if(chargeDetailForm.getIsOwner() == 1){
            return chargeDetailService.findOwe2App(chargeDetailForm);
        }
        if(chargeDetailForm.getRoomId() == null && chargeDetailForm.getIsOwner() == 0){
            return JsonResult.ok();
        }
        if(chargeDetailForm.getRoomId().equals("") && chargeDetailForm.getIsOwner() == 0){
            return JsonResult.ok();
        }
        return chargeDetailService.findOwe2App(chargeDetailForm);
    }

    @PostMapping("/findPaid")
    public JsonResult findPaid(ChargeDetailForm chargeDetailForm){
        return chargeDetailService.findPaid(chargeDetailForm);
    }

    @PostMapping("/findPaidByCycle")
    public JSONObject findPaidByCycle(StatisticsForm statisticsForm){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg",0);
        if(statisticsForm.getSType().equals("month")){
            if(StringUtils.isEmpty(statisticsForm.getSTime())){
                statisticsForm.setSTime(statisticsForm.getSYear() + "-01");
            }
            if (StringUtils.isEmpty(statisticsForm.getETime())){
                statisticsForm.setETime(statisticsForm.getSYear() + "-12");
            }
            List<StatisticsVo> pays2YearCycle = chargeDetailService.findPays2YearCycle(statisticsForm);

            jsonObject.put("count",pays2YearCycle.size());
            jsonObject.put("data",pays2YearCycle);
        }
        if(statisticsForm.getSType().equals("day")){
            if (StringUtils.isEmpty(statisticsForm.getETime())){
                statisticsForm.setSTime(format.format(firstDate()));
                statisticsForm.setETime(format.format(endDate()));
            }else{
                String[] split = statisticsForm.getETime().split("-");
                statisticsForm.setSTime(getFirstDayOfMonth1(Integer.parseInt(split[0]),Integer.parseInt(split[1])));
                statisticsForm.setETime(getLastDayOfMonth1(Integer.parseInt(split[0]),Integer.parseInt(split[1])));
            }
            List<StatisticsVo> pays2MonthCycle = chargeDetailService.findPays2MonthCycle(statisticsForm);
            jsonObject.put("count",pays2MonthCycle.size());
            jsonObject.put("data",pays2MonthCycle);
        }
        return jsonObject;
    }

    @GetMapping("/outputExcel")
    public void outputExcel(HttpServletResponse response, String villageId, String sYear, String itemsId,String SType,String eTime) throws IOException {
        List<StatisticsVo> svo = new ArrayList<>();
        List<ChargeData> chargeData = new ArrayList<>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String type = "";
        StatisticsForm statisticsForm = new StatisticsForm();
        statisticsForm.setItemsId(itemsId);
        statisticsForm.setVillageId(villageId);
        if(SType.equals("month")){
            type = sYear;
            statisticsForm.setSTime(sYear + "-01");
            statisticsForm.setETime(sYear + "-12");
            svo = chargeDetailService.findPays2YearCycle(statisticsForm);
        }
        if(SType.equals("day")){
            type = eTime;
            if (StringUtils.isEmpty(eTime)){
                statisticsForm.setSTime(format.format(firstDate()));
                statisticsForm.setETime(format.format(endDate()));
            }else{
                String[] split = eTime.split("-");
                statisticsForm.setSTime(getFirstDayOfMonth1(Integer.parseInt(split[0]),Integer.parseInt(split[1])));
                statisticsForm.setETime(getLastDayOfMonth1(Integer.parseInt(split[0]),Integer.parseInt(split[1])));
            }
            svo = chargeDetailService.findPays2MonthCycle(statisticsForm);
        }

        for (StatisticsVo s : svo) {
            ChargeData data = new ChargeData();
            data.setCtime(s.getCtime());
            data.setItemsName(s.getItemsName());
            data.setSubtotal(s.getSubtotal());
            chargeData.add(data);
        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(type+"缴费报表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), ChargeData.class).registerWriteHandler(new ColumnWidthStyleStrategy()).sheet(type).doWrite(chargeData);
    }

    public Date firstDate(){
        Calendar cale = Calendar.getInstance();
        cale.setTime(new Date());
        cale.add(Calendar.MONTH, 0);
        cale.set(Calendar.DAY_OF_MONTH, 1);
        return cale.getTime(); // 当月第一天 2019-02-01
    }

    public Date endDate(){
        Calendar cale = Calendar.getInstance();
        cale.setTime(new Date());
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        return cale.getTime(); // 当月最后一天 2019-02-01
    }

    public static String getFirstDayOfMonth1(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最小天数
        int firstDay = cal.getMinimum(Calendar.DATE);
        //设置日历中月份的最小天数
        cal.set(Calendar.DAY_OF_MONTH,firstDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }

    public static String getLastDayOfMonth1(int year, int month) {
        Calendar cal = Calendar.getInstance();
        //设置年份
        cal.set(Calendar.YEAR, year);
        //设置月份
        cal.set(Calendar.MONTH, month-1);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DATE);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        //格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(cal.getTime());
    }
}
